package com.yuan.java.thread.threadNotSafe;

import org.junit.Test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadTest1 {

    /**
     * lock 锁
     */
    @Test
    public void main0() {
        Runnable runnable = new Runnable() {
            Count0 count = new Count0();
            //初始化lock锁机制
            private Lock lock = new ReentrantLock();

            public void run() {
                //进行锁定
                lock.lock();
                count.count();
                //释放锁 如果不释放锁可以看到只有一个线程被执行了
                lock.unlock();
            }
        };
        for (int i = 0; i < 10; i++) {
            new Thread(runnable).start();
        }
    }

}

/**
 * 线程调用例子
 */
//public class Consumer implements Runnable {
//
//    private Lock lock;
//    public Consumer(Lock lock) {
//        this. lock = lock;
//    }
//    @Override
//    public void run() {
//        // TODO Auto-generated method stub
//        int count = 10;
//        while( count > 0 ) {
//            try {
//                lock.lock();
//                count --;
//                System. out.print( "B");
//            } finally {
//                lock.unlock(); //主动释放锁
//                try {
//                    Thread. sleep(91L);
//                } catch (InterruptedException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
//        }
//
//    }
//
//}
//